package com.bhs.sansong.ui.findLogistics;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.ListPrivateLinesAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.Constants;
import com.bhs.sansong.bean.CompaniesInfo;
import com.bhs.sansong.bean.CompaniesInfoData;
import com.bhs.sansong.bean.CompanyInfo;
import com.bhs.sansong.bean.CompanyInformation;
import com.bhs.sansong.bean.ListPrivateLines;
import com.bhs.sansong.bean.MenuBean;
import com.bhs.sansong.bean.OperationEvent;
import com.bhs.sansong.bean.Options;
import com.bhs.sansong.bean.PrivateLines;
import com.bhs.sansong.bean.TypeBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.dialog.BottomSelectListDialog;
import com.bhs.sansong.ui.dialog.BottomSelectPhone2Dialog;
import com.bhs.sansong.ui.dialog.FiltratePopupView;
import com.bhs.sansong.ui.dialog.MyClickListener2;
import com.bhs.sansong.ui.shipments.IssueNewOrderActivity;
import com.bhs.sansong.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.SimpleCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 物流公司列表
 */
public class LogisticsCompaniesListActivity extends BaseActivity implements NetCallBack, View.OnClickListener {


    private TextView mTvTitle;
    private FrameLayout mFlShare;
    private EditText mEtSearch;
    private LinearLayout mLlCity;
    private TextView mTvCity;
    private LinearLayout mLlGarden;
    private TextView mTvGarden;
    private LinearLayout mLlSort;
    private TextView mTvSort;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRvList;
    private ListPrivateLinesAdapter mAdapter;
    private int page = 1;
    private String startCity;
    private String endCity;
    private String end_county;
    private String companyName;
    private int type;//1 指派  2找物流
    private Options options;
    private List<TypeBean> mList = new ArrayList<>();
    private List<TypeBean> mCityList = new ArrayList<>();
    private List<TypeBean> mParkList = new ArrayList<>();

    @Override
    public int initLayout() {
        return R.layout.activity_logistics_companies_list;
    }

    @Override
    public void initView() {
        end_county = getIntent().getStringExtra("end_county");
        type = getIntent().getIntExtra("type", 1);
        startCity = getIntent().getStringExtra("startCity");
        endCity = getIntent().getStringExtra("endCity");
        companyName = getIntent().getStringExtra("companyName");
        companyName = !TextUtils.isEmpty(companyName) ? companyName : "";
        mTvTitle = findViewById(R.id.tv_title);
        if (!TextUtils.isEmpty(startCity)) {
            mTvTitle.setText(String.format("%s-%s", startCity, endCity));
        }

        mFlShare = findViewById(R.id.fl_share);
        mEtSearch = findViewById(R.id.et_search);
        mLlCity = findViewById(R.id.ll_city);
        mTvCity = findViewById(R.id.tv_city);
        mLlGarden = findViewById(R.id.ll_garden);
        mTvGarden = findViewById(R.id.tv_garden);
        mLlSort = findViewById(R.id.ll_sort);
        mTvSort = findViewById(R.id.tv_sort);
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRvList = findViewById(R.id.rv_list);
        mLlCity.setOnClickListener(this);
        mLlGarden.setOnClickListener(this);
        mLlSort.setOnClickListener(this);
        mList.add(new TypeBean("综合排序", "1"));
        mList.add(new TypeBean("距离排序", "2"));
        mList.add(new TypeBean("评分排序", "3"));
        mList.add(new TypeBean("单量排序", "4"));
    }

    @Override
    public void initData() {
        mAdapter = new ListPrivateLinesAdapter(type);
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter.setEmptyView(LayoutInflater.from(mActivity).inflate(R.layout.layout_empty, null));
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData(companyName);
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                loadData(companyName);
            }
        }, mRvList);


        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PrivateLines data = mAdapter.getData().get(position);
                if (type == 1) {
                    CompanyInfo companyInfo = data.getLogistics_info().getCompany_info();
                    CompanyInformation companyInformation = new CompanyInformation(companyInfo.getCompany_pic(),
                            companyInfo.getAddress(), String.valueOf(companyInfo.getLogistics_id()),
                            data.getLine_info().getLine_id(), companyInfo.getCompany_name());
                    companyInformation.setStartCity(data.getLine_info().getStart_city());
                    companyInformation.setEndCity(data.getLine_info().getEnd_city());
                    Intent i = new Intent();
                    i.putExtra("info", companyInformation);
                    setResult(3, i);
                    finish();
                } else {
                    CompanyInfo companyInfo;
                    companyInfo = data.getLogistics_info();
                    if (companyInfo == null || companyInfo.getCompany_pic() == null) {
                        companyInfo = data.getLogistics_info().getCompany_info();
                    }
                    startActivity(new Intent(mActivity, CompanyDetailsActivity.class)
                            .putExtra("logistics_id", companyInfo.getLogistics_id()));
                }
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PrivateLines data = mAdapter.getData().get(position);
                CompanyInfo companyInfo = mAdapter.getData().get(position).getLogistics_info().getCompany_info();
                if (view.getId() == R.id.ll_contact) {
                    contactImmediately(data);
                } else if (view.getId() == R.id.tv_consent) {
                    CompanyInformation companyInformation = new CompanyInformation(companyInfo.getCompany_pic(),
                            companyInfo.getAddress(), String.valueOf(companyInfo.getLogistics_id()),
                            data.getLine_info().getLine_id(), companyInfo.getCompany_name());
                    companyInformation.setStartCity(data.getLine_info().getStart_city());
                    companyInformation.setEndCity(data.getLine_info().getEnd_city());
                    startActivity(new Intent(mActivity, IssueNewOrderActivity.class)
                            .putExtra("order_type", "1")
                            .putExtra("place_order_type", "1")
                            .putExtra("networkCity", data.getLine_info().getEnd_city())
                            .putExtra("companyInfo", companyInformation));
                }
            }
        });

        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索要做的操作
                    page = 1;
                    loadData(mEtSearch.getText().toString());
                    return true;
                }
                return false;
            }
        });
        loadingPopupShow();
        loadData(companyName);
        if (TextUtils.isEmpty(companyName) && !TextUtils.isEmpty(startCity)) {
            Map<String, Object> map1 = new ArrayMap<>();
            map1.put("start_city", startCity);
            map1.put("end_city", endCity);
            networkRequest(netApi.get_specialLine_options(map1), this, 666);
        } else {
            findViewById(R.id.ll_screen).setVisibility(View.GONE);
        }
    }

    private BottomSelectListDialog listDialog;


    BottomSelectPhone2Dialog bottomSelectDialog;
    BasePopupView basePopupView;

    private void contactImmediately(PrivateLines data) {
        if (basePopupView == null) {
            bottomSelectDialog = new BottomSelectPhone2Dialog(this, data.getLogistics_info().getCompany_info().getMobile(), data.getLogistics_info().getCompany_info().getFixed_telephone(), data.getLine_info().getLine_mobile());
            basePopupView = new XPopup.Builder(this)
                    .asCustom(bottomSelectDialog)
                    .show();
        } else {
            basePopupView.show();
        }
    }


    Map<String, Object> map = new ArrayMap<>();

    private void loadData(String search_key) {
        map.put("page", String.valueOf(page));
        map.put("limit", "10");
        if (TextUtils.isEmpty(companyName) && !TextUtils.isEmpty(startCity)) {
            map.put("start_city", startCity);
            map.put("end_city", endCity);
            if (!TextUtils.isEmpty(end_county) && !end_county.equals("全市")) {
                map.put("end_area", end_county);
            }
        }
        map.put("search_key", search_key);
        map.put("sort", mTvSort.getTag() != null ? mTvSort.getTag() : "");
        map.put("start_area", mTvCity.getTag() != null ? mTvCity.getTag() : "");
        map.put("park_id", mTvGarden.getTag() != null ? mTvGarden.getTag() : "");
        map.put("user_lng", Constants.longitude);
        map.put("user_lat", Constants.latitude);
        if (TextUtils.isEmpty(companyName)) {
            networkRequest(netApi.get_special_line_by_json(map), this);
        } else {
            networkRequest(netApi.get_logistics_companys_by_json(map), this);
        }
    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            loadingPopupDismiss();
            ListPrivateLines data = new Gson().fromJson(json, ListPrivateLines.class);
            mRefreshLayout.setRefreshing(false);
            if (data.isStatus()) {
                if (page == 1) {
                    mAdapter.setNewData(data.getData().getList());
                } else {
                    mAdapter.loadMoreComplete();
                    mAdapter.addData(data.getData().getList());
                }
                if (mAdapter.getData().size() >= data.getData().getTotal_count()) {
                    mAdapter.loadMoreEnd();
                }
            }
        } else {
            options = new Gson().fromJson(json, Options.class);
            int cityNum = 0;
            for (Options.DataDTO.AreaNumDTO areaNumDTO : options.getData().getArea_num()) {
                if (areaNumDTO.getLine_num() > 0) {
                    cityNum += areaNumDTO.getLine_num();
                    mCityList.add(new TypeBean(String.format("%s(%s)", areaNumDTO.getArea_name(), areaNumDTO.getLine_num()), areaNumDTO.getArea_name(), false));
                }
            }
            mCityList.add(0, new TypeBean(String.format("%s(%s)", startCity, cityNum), true));
            mTvCity.setText(String.format("%s(%s)", startCity, cityNum));
            int parkNum = 0;
            for (Options.DataDTO.ParkListDTO areaNumDTO : options.getData().getPark_list()) {
                if (areaNumDTO.getNum() > 0) {
                    parkNum += areaNumDTO.getNum();
                    mParkList.add(new TypeBean(String.format("%s(%s)", areaNumDTO.getName(), areaNumDTO.getNum()), String.valueOf(areaNumDTO.getId()), false));
                }
            }
            mParkList.add(0, new TypeBean(String.format("%s(%s)", "全部", parkNum), true));
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
        mRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.ll_city) {
            if (options == null) {
                ToastUtil.show("正在获取数据");
                return;
            }
            showPartShadow(view, mCityList, 1);
        } else if (view.getId() == R.id.ll_garden) {
            if (options == null) {
                ToastUtil.show("正在获取数据");
                return;
            }

            showPartShadow(view, mParkList, 2);
        } else {
            showPartShadow(view, mList, 3);
        }
    }

    private FiltratePopupView filtratePopupView;

    private void showPartShadow(final View v, List<TypeBean> mList, int type) {
        filtratePopupView = (FiltratePopupView) new XPopup.Builder(mActivity)
                .atView(v)
                .asCustom(new FiltratePopupView(mActivity, mList, type));
        filtratePopupView.setMyClickListener(new MyClickListener2() {
            @Override
            public void onClick(String id, String info) {
                filtratePopupView.dismiss();
                if (type == 1) {
                    if (!mTvCity.getText().toString().equals(info)) {
                        mTvCity.setTag(id);
                        loadData("");
                    }
                    mTvCity.setText(info);
                } else if (type == 2) {
                    if (!mTvGarden.getText().toString().equals(info)) {
                        mTvGarden.setTag(id);
                        loadData("");
                    }
                    mTvGarden.setText(info);
                } else {
                    if (!mTvSort.getText().toString().equals(info)) {
                        mTvSort.setTag(id);
                        loadData("");
                    }
                    mTvSort.setText(info);
                }
            }
        });
        filtratePopupView.show();
    }
}